<template>
  <div class="project">
    <div class="left">
      <div
        class="from"
        v-for="(item, index) in templateInfo"
        :key="index"
      >
        <div class="title">{{ item.name }}</div>
        <div
          class="item"
          v-for="(data, i) in item.list"
          :key="i"
        >
          <div class="item-title">
            <el-checkbox
              true-label="1"
              false-label="0"
              v-model="data.selected"
              :disabled="
                !canCheck(item.list, i, index) || isDetail
              "
              @change="handleCheckboxChange(data, index)"
            ></el-checkbox>
            <div
              class="name"
              :class="{
                active: !canCheck(item.list, i, index)
              }"
            >
              {{ data.nodeName }}
              <b v-if="data.hasMain == '1'">(关键节点)</b>
              <span v-if="data.createTime && index !== 0"
                >转入时间：{{ data.createTime }}</span
              >
            </div>
          </div>
          <!-- <template v-if="index !== 0"> -->
          <template>
            <div
              class="content"
              v-show="
                shouldShowContent(item.list, i, index)
              "
            >
              <el-row>
                <el-col :span="6">
                  <p>办理情况</p>
                  <el-radio-group
                    v-model="data.nodeStatus"
                    :disabled="isDetail"
                  >
                    <el-radio label="已办结"
                      >已办结</el-radio
                    >
                    <el-radio
                      v-if="data.hasTolerance == '1'"
                      label="容缺补办"
                      >容缺补办</el-radio
                    >
                    <el-radio label="无需办理"
                      >无需办理</el-radio
                    >
                  </el-radio-group>
                </el-col>
                <el-col :span="9">
                  <p>当前卡点</p>
                  <el-input
                    type="textarea"
                    class="resize-textarea"
                    v-model="data.nodeRemarks"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-col>
                <el-col
                  :span="9"
                  v-show="data.nodeStatus === '已办结'"
                >
                  <p>实际完成时间</p>
                  <el-date-picker
                    v-model="data.nodeFinishTime"
                    type="date"
                    placeholder="年/月/日"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    :disabled="isDetail"
                  >
                  </el-date-picker>
                </el-col>
              </el-row>
            </div>
          </template>
        </div>
      </div>
    </div>
    <div class="right">
      <div
        class="box"
        v-for="(item, index) in resourceDictData"
        :key="index"
      >
        <div class="project-part-title">
          {{ item.dictName }}
        </div>
        <div class="checkbox">
          <el-checkbox-group v-model="constructionElements">
            <el-checkbox
              v-for="(data, i) in item.resourceDictItems"
              :key="i"
              :label="data.dictValue"
              :disabled="
                !isProjectInStorageSelected || isDetail
              "
              >{{ data.dictText }}
            </el-checkbox>
            <el-input
              v-show="isOtherChecked"
              type="textarea"
              class="resize-textarea"
              v-model="constructionElementsValue"
              placeholder="请输入"
              :disabled="isDetail"
            ></el-input>
          </el-checkbox-group>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  getTemplateInfo,
  getDictInfo
} from '@/api/dataManagement'

export default {
  name: 'project',
  props: {
    currentTab: Number,
    isDetail: Boolean,
    detailInfo: Object,
    isEdit: Boolean
  },
  data() {
    return {
      fundBuildSource: '其他',
      landingMethod: '',
      templateInfo: [],
      resourceDictData: [],
      processNodeRels: [],
      constructionElements: [],
      constructionElementsValue: ''
    }
  },
  computed: {
    isProjectInStorageSelected() {
      const firstGroup = this.templateInfo[1]?.list || []
      const projectNode = firstGroup[0] // 第一个节点
      console.log(projectNode?.selected)
      return projectNode?.selected == '1'
    },
    isOtherChecked() {
      return this.constructionElements.includes('pce012')
    }
  },
  watch: {
    // currentTab(newVal, oldVal) {
    //   this.processNodeRels = this.restoreOriginalData(
    //     this.templateInfo
    //   )
    // },
    detailInfo(newVal) {
      console.log(' detail info changed: ', newVal)
      console.log(newVal?.baseMess?.pkid, 'dasad')
      if (newVal?.baseMess?.pkid) {
        setTimeout(() => {
          const groupedData = newVal.processNodeRels.reduce(
            (acc, item) => {
              const { nodeType } = item
              if (!acc[nodeType]) {
                acc[nodeType] = []
              }
              acc[nodeType].push(item)
              return acc
            },
            {}
          )
          const self = this
          this.templateInfo = Object.keys(groupedData).map(
            (key, index) => {
              return {
                name: key,
                list: groupedData[key].map((data, i) => {
                  self.$set(
                    data,
                    'nodeFinishTime',
                    data.nodeFinishTime || ''
                  )
                  self.$set(
                    data,
                    'nodeRemarks',
                    data.nodeRemarks || ''
                  )
                  return data
                })
              }
            }
          )
          this.constructionElements =
            newVal.baseMess.constructionElements.split(',')
          this.constructionElementsValue =
            newVal.baseMess.constructionElementsValue
          this.processNodeRels = this.restoreOriginalData(
            this.templateInfo
          )
        }, 30)
      }
    }
  },
  created() {
    if (!this.isEdit) this.getTemplate()
    this.getDictData()
  },

  methods: {
    // 还原数据
    restoreOriginalData(templateInfo) {
      return templateInfo.flatMap((group, i) => {
        return group.list.map((item, index) => {
          const newItem = { ...item }
          // 如果是新增状态，并且 item 中有 pkid 字段
          if (!this.isEdit && 'pkid' in newItem) {
            console.log(11)
            newItem.pkid = ''
          }
          newItem.processNodeId = newItem.pkid
          if (index === 0 && i === 0) {
            newItem.nodeStatus = '已办结'
          }

          return newItem
        })
      })
    },
    handleCheckboxChange(data, index) {
      console.log(index)
      if (!index) {
        if (!data.selected) {
          // 如果取消勾选，清空相关字段
          data.nodeStatus = ''
          data.nodeRemarks = ''
          data.nodeFinishTime = null
        }
      }
    },
    canCheck(list, currentIndex, groupIndex) {
      // 第一个分组(index === 0)，不允许勾选
      // if (groupIndex === 0) return false

      // 第二个分组(index === 1)
      // 改为第一个分组(index === 1)
      if (groupIndex === 0) {
        if (currentIndex === 0) {
          // 第一个节点始终可以勾选
          return true
        } else {
          // 后续节点必须上一节点 nodeStatus 存在
          const prevItem = list[currentIndex - 1]
          return prevItem.selected && prevItem.nodeStatus
        }
      }

      // 第三个及以后分组(index >= 2)
      // 改为第二个及以后分组(index >= 2)
      if (groupIndex >= 1) {
        if (currentIndex === 0) {
          // 当前分组第一个节点：依赖上一分组最后一个节点的 nodeStatus
          const prevGroup =
            this.templateInfo[groupIndex - 1]
          const lastItemOfPrevGroup =
            prevGroup?.list[prevGroup.list.length - 1]
          return (
            lastItemOfPrevGroup.selected &&
            lastItemOfPrevGroup.nodeStatus
          )
        } else {
          // 非第一个节点：依赖当前分组前一个节点的 nodeStatus
          const prevItem = list[currentIndex - 1]
          return prevItem.selected && prevItem.nodeStatus
        }
      }

      return true
    },
    shouldShowContent(list, currentIndex, groupIndex) {
      // // 第一个分组不展示内容区域
      // if (groupIndex === 0) return false

      // 第二个分组（立项）
      // 第一个分组
      if (groupIndex === 0) {
        // 第一个节点(i === 0)，只要 selected 为 true 就展示
        if (currentIndex === 0) {
          return list[currentIndex]?.selected
        }
        // 其他节点(i >= 1)，需要上一项的 nodeStatus 存在
        const prevItem = list[currentIndex - 1]
        console.log(
          prevItem.selected && prevItem.nodeStatus,
          '第二分组'
        )
        return (
          prevItem.selected &&
          prevItem.nodeStatus &&
          !this.isDetail
        )
      }

      // 第三个及以后分组(index >= 2)
      // 改为第二个及以后分组(index >= 1)
      if (groupIndex >= 1) {
        // 所有节点都需要依赖上一项的 nodeStatus
        if (currentIndex > 0) {
          const prevItem = list[currentIndex - 1]
          console.log(
            prevItem.selected && prevItem.nodeStatus,
            '第三个及以后分组'
          )
          return (
            prevItem.selected &&
            prevItem.nodeStatus &&
            !this.isDetail
          )
        }
        // 如果是当前分组第一个节点，则也需要上一分组最后一个节点的 nodeStatus
        const prevGroup = this.templateInfo[groupIndex - 1]
        const lastItemOfPrevGroup =
          prevGroup?.list[prevGroup.list.length - 1]
        console.log(
          lastItemOfPrevGroup.selected &&
            lastItemOfPrevGroup.nodeStatus,
          '如果是当前分组第一个节点'
        )
        return (
          lastItemOfPrevGroup.selected &&
          lastItemOfPrevGroup.nodeStatus &&
          !this.isDetail
        )
      }

      return false
    },
    // 初始化信息
    initData({ fundBuildSource, landingMethod }) {
      console.log('init ', fundBuildSource, landingMethod)
      // 资金来源
      this.fundBuildSource = fundBuildSource || '其他'
      // 拿地方式
      this.landingMethod = landingMethod
      // this.getTemplate()
      // this.getDictData()
    },
    // 获取模板信息
    getTemplate() {
      console.log('get template info')
      getTemplateInfo({
        fundBuildSource: this.fundBuildSource,
        landingMethod: this.landingMethod
      }).then((res) => {
        const groupedData = res.data.reduce((acc, item) => {
          const { nodeType } = item
          if (!acc[nodeType]) {
            acc[nodeType] = []
          }
          acc[nodeType].push(item)
          return acc
        }, {})
        this.templateInfo = Object.keys(groupedData).map(
          (key, index) => {
            // const isFirstChild = index === 0 ? '1' : '0'
            return {
              name: key,
              list: groupedData[key].map((data, i) => {
                // data.selected = isFirstChild
                data.selected = false
                data.nodeStatus = ''
                data.nodeRemarks = ''
                data.nodeFinishTime = null
                data.createTime = ''
                return data
              })
            }
          }
        )
        this.processNodeRels = this.restoreOriginalData(
          this.templateInfo
        )
      })
    },
    //   获取字典信息
    getDictData() {
      let dictCode = ''
      if (
        this.fundBuildSource == '政府投资' ||
        this.landingMethod == '其他'
      ) {
        dictCode = 'project_construction_elements'
      } else if (
        this.fundBuildSource == '企业投资' &&
        this.landingMethod == '拿地'
      ) {
        dictCode = 'project_enterprise_investment_nd'
      } else if (
        this.fundBuildSource == '企业投资' &&
        this.landingMethod == '入驻载体'
      ) {
        dictCode = 'project_enterprise_investment_rzzt'
      } else if (
        this.fundBuildSource == '平台公司自筹' &&
        this.landingMethod == '拿地'
      ) {
        dictCode = 'project_platform_investment_nd'
      } else if (
        this.fundBuildSource == '平台公司自筹' &&
        this.landingMethod == '入驻载体'
      ) {
        dictCode = 'project_enterprise_investment_rzzt'
      }
      getDictInfo(dictCode).then((res) => {
        this.resourceDictData = res.data
      })
    }
  }
}
</script>
<style scoped lang="scss">
.project {
  width: 100%;
  padding: 20px 20px 0 20px;
  display: flex;
  box-sizing: border-box;
  font-size: 16px;

  font-weight: 500;
  color: #4c565c;

  > .left {
    width: 70%;
    // margin: 10px 0;

    > .from {
      width: 100%;
      margin-bottom: 10px;

      > .title {
        position: relative;
        margin-bottom: 10px;
        line-height: 16px;

        &::after {
          content: '';
          width: 4px;
          height: 16px;
          background: linear-gradient(
            180deg,
            #40ebff,
            #bcf8ff
          );
          position: absolute;
          left: -10px;
          top: 0;
        }
      }

      > .item {
        font-size: 14px;
        margin-bottom: 30px;

        > .item-title {
          display: flex;
          align-items: center;
          margin-bottom: 10px;

          > .name {
            margin-left: 8px;
            font-size: 14px;

            &.active {
              color: #bec3cf;
            }

            > span {
              margin-left: 10px;
              color: #bec3cf;
              font-size: 14px;
            }
          }
        }

        > .content {
          padding-left: 20px;
          box-sizing: border-box;

          p {
            margin: 0 0 8px;
          }

          .el-col {
            // padding-right: 20px;
            box-sizing: border-box;

            &:last-child {
              padding-right: 0;
            }
          }
        }
      }
    }
  }

  > .right {
    flex: 1;

    > .box {
      width: 100%;

      > .project-part-title {
        font-size: 16px;
        color: #4c565c;
        margin-bottom: 24px;
        position: relative;
        line-height: 16px;
        padding-left: 11px;

        &::after {
          background: linear-gradient(
            180deg,
            #40ebff,
            #bcf8ff
          );
          position: absolute;
          content: '';
          width: 4px;
          height: 16px;
          top: 0;
          left: 0;
        }
      }
    }
  }
}

:deep().el-textarea__inner {
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 400;
  width: 320px !important;
}

.checkbox {
  :deep().el-checkbox {
    width: 100%;
    margin-bottom: 10px;
  }
}

:deep(.el-input__inner) {
  width: 320px !important;
  height: 32px !important;
}

:deep(.el-input__icon) {
  line-height: 32px !important;
}
</style>
